﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using MonkeyShop.Web.Biz.Data;
using MonkeyShop.Web.Models;

namespace MonkeyShop.Web.Biz
{
    public class DesktopBuilderBiz
    {
        /// <summary>
        /// Gets the products in category.
        /// </summary>
        /// <param name="catId">The cat identifier.</param>
        /// <returns></returns>
        public static List<ProductModel> GetProductsInCategory(int catId)
        {
            if (catId <= 0) return null;
            using (var db = new MonkeyShopWebEntities())
            {
                var products = from p in db.Products
                    join pc in db.ProductToCategories on p.Id equals pc.ProductId
                    where pc.CategoryId == catId
                    orderby p.Price
                    select new ProductModel {Id = p.Id, Name = p.Name, Price = p.Price};
                return products.ToList();
            }
        }

        /// <summary>
        /// Gets the desktop products.
        /// </summary>
        /// <param name="desktopModel">The desktop model.</param>
        /// <returns></returns>
        public static List<ProductDetailsModel> GetDesktopProducts(DesktopModel desktopModel)
        {
            if (desktopModel == null) return null;
            List<ProductDetailsModel> productDetails;
            using (var db = new MonkeyShopWebEntities())
            {
                var products = from p in db.Products
                               join pc in db.ProductToCategories on p.Id equals pc.ProductId
                               join c in db.Categories on pc.CategoryId equals c.Id
                               where desktopModel.ProductIds.Contains(p.Id )
                               orderby c.SortOrder
                               select new ProductDetailsModel { Id = p.Id, Name = p.Name, Image = p.Image, Price = p.Price, CategoryName = c.Name};
                productDetails = products.ToList();
            }

            var results = new List<ProductDetailsModel>();
            foreach (var p in productDetails)
            {
                results.Add(p);
                var count = desktopModel.ProductIds.Where(id => id == p.Id).Count();
                if (count <= 1) continue;
                for (var i = 1; i < count; i++)
                {
                    var clone = new ProductDetailsModel { Id = p.Id, Name = p.Name, Image = p.Image, Price = p.Price, CategoryName = p.CategoryName };
                    results.Add(clone);
                }
            }

            return results;
        }
    }
}
